package com.blue.wechat.pay;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.core.util.DateUtil;
import com.blue.core.util.MoneyUtil;
import com.blue.core.util.ReflectionUtil;

/**
 * 微信支付工具类
 * 
 * @author zhengj
 * @since 1.0 2017年1月30日
 */
public class WechatPayUtil
{
	private static Logger logger = LoggerFactory.getLogger(WechatPayUtil.class);
	
	private WechatPayUtil()
	{
	}
	
	/**
	 * 对象 ==> XML
	 * 
	 * @param object 对像
	 * @param key 密钥
	 * @return XML
	 */
	public static String toXml(Object object, String key)
	{
		SortedSet<String> set = new TreeSet<String>();
		StringBuilder xml = new StringBuilder(1024).append("<xml>");
		for (Method getter : ReflectionUtil.getterList(object.getClass()))
		{
			String fieldName = ReflectionUtil.field(getter);
			String column = ReflectionUtil.fieldToColumn(fieldName);
			
			try
			{
				String value = toString(getter.invoke(object));
				if (!fieldName.equals("sign") && value != null && !value.equals(""))
				{
					set.add(column + "=" + value);
					cdata(xml, column, value);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
		String md5 = DigestUtils.md5Hex(StringUtils.join(set, "&") + "&key=" + key).toUpperCase();
		logger.info("生成签名：{}", md5);

		cdata(xml, "sign", md5);
		xml.append("</xml>");
		return xml.toString();
	}
	
	/**
	 * JSAPI签名
	 * 
	 * @param map
	 * @return
	 */
	public static String jsapiSign(Map<String, String> map)
	{
		SortedSet<String> set = new TreeSet<String>();
		for (Map.Entry<String, String> entry : map.entrySet())
		{
			set.add(entry.getKey() + "=" + entry.getValue());
		}
		
		String sha1 = DigestUtils.sha1Hex(StringUtils.join(set, "&"));
		logger.info("生成JS签名：{}", sha1);
		map.put("signature", sha1);
		return sha1;
	}
	
	/**
	 * 从对象生成签名
	 * 
	 * @param object
	 * @param key
	 * @return
	 */
	public static String sign(Object object, String key)
	{
		SortedSet<String> set = new TreeSet<String>();
		for (Method getter : ReflectionUtil.getterList(object.getClass()))
		{
			String fieldName = ReflectionUtil.field(getter);
			
			try
			{
				String value = toString(getter.invoke(object));
				if (!fieldName.equals("sign") && value != null && !value.equals(""))
				{
					set.add(fieldName + "=" + value);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
		String extra = "";
		if (key != null && !key.equals(""))
			extra = "&key=" + key;
			
		String md5 = DigestUtils.md5Hex(StringUtils.join(set, "&") + extra).toUpperCase();
		logger.info("生成签名：{}", md5);

		return md5;
	}
	
	/**
	 * XML ==> 对象
	 * 
	 * @param clazz 对象类型
	 * @param key 密钥
	 * @param xml XML
	 * @return 对象
	 */
	public static <T> T toObject(Class<T> clazz, String key, String xml)
	{
		Map<String, String> map = new HashMap<>();
		SortedSet<String> set = new TreeSet<String>();
		String sign = null;
		
		Document doc = Jsoup.parse(xml);
		Element root = doc.getElementsByTag("xml").first();
		for (Element node : root.children())
		{
			String tag = node.tagName();
			String value = node.text();
			if (tag.equals("sign"))
			{
				sign = value;
				map.put(tag, sign);
				continue;
			}
			
			if (value != null && !value.equals(""))
			{
				set.add(tag + "=" + value);
				map.put(tag, value);
			}
		}
		
		String extra = "";
		if (key != null && !key.equals(""))
			extra = "&key=" + key;

		String md5 = DigestUtils.md5Hex(StringUtils.join(set, "&") + extra).toUpperCase();
		logger.info("来源签名：{}", sign);
		logger.info("验证签名：{}", md5);
		
		if (!md5.equals(sign))
			throw new IllegalArgumentException("签名验证失败");
		
		T obj = null;
		try
		{
			obj = clazz.newInstance();

			for (Method setter : clazz.getMethods())
			{
				if (!setter.getName().startsWith("set"))
					continue;
				
				String fieldName = ReflectionUtil.field(setter);
				String column = ReflectionUtil.fieldToColumn(fieldName);
				String strValue = map.get(column);
				if (strValue == null || strValue.equals(""))
					continue;
				
				Class<?> type = setter.getParameterTypes()[0];
				setter.invoke(obj, toObject(type, strValue));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	private static String toString(Object value)
	{
		if (value == null)
			return null;
		
		if (value.getClass() == String.class)
			return (String)value;
		
		if (value.getClass() == Double.class)
			return MoneyUtil.format((Double)value);
		
		if (value instanceof Date)
			return DateUtil.formatDateTime((Date)value);
		
		return value.toString();
	}
	
	private static Object toObject(Class<?> clazz, String strValue)
	{
		if (strValue == null)
			return null;
		
		if (clazz == String.class)
			return strValue;
		
		if (clazz == Double.class)
			return Double.valueOf(strValue);
		
		if (clazz == Integer.class)
			return Integer.valueOf(strValue);
		
		if (clazz == Long.class)
			return Long.valueOf(strValue);
		
		if (clazz == Float.class)
			return Float.valueOf(strValue);
		
		if (clazz == Boolean.class)
			return Boolean.valueOf(strValue);
		
		if (clazz == Date.class)
			return DateUtil.parseDateTime(strValue);
		
		if (clazz.isEnum())
			return ReflectionUtil.valueOfEnum(clazz, strValue);
		
		return strValue;
	}
	
	private static void cdata(StringBuilder xml, String tag, String value)
	{
		xml.append("<").append(tag).append(">");
		xml.append("<![CDATA[").append(value == null ? "" : value).append("]]>");
		xml.append("</").append(tag).append(">");
		xml.append("\n");
	}
	
}
